<?php
/**
 * Created by PhpStorm.
 * User: zd
 * Date: 2018/8/14
 * Time: 11:43
 */

namespace app\api\controller\v1;
use app\api\controller\BaseController;
use app\api\model\Category as CategoryModel;
use app\api\model\Product as ProductModel;
use app\api\model\WorkUser;
use app\api\service\Property;
use app\api\validate\CategoryParameter;
use app\api\validate\CategoryUpdateParameter;
use app\api\validate\IDMustBePositiveInt;
use app\lib\exception\CategoryException;
use app\api\service\Token;
use app\lib\exception\ProductException;
use app\lib\exception\SuccessMessage;
use think\Cache;
use think\Exception;
use think\Hook;

class Category extends BaseController
{
    /**
     * 权限判断
     * @var array
     */
    protected $beforeActionList=[
        'checkPrimaryScope' => ['only'=>'getCategoryByManager,createCategory,updateCategory,deleteCategory,getProperty,getPropertyByCategory'],
        'checkExclusiveScope' => ['only'=>'getAllCategory'],
        'checkAuthorize'=>['only'=>'getCategoryByUser']
    ];

    /**
     * 获取分类(商城)
     * @return false|static[]
     * @throws CategoryException
     */
    public function getAllCategory($wu_id){
        $uid =Token::getCurrentUid();
        $t_id = Token::getCurrentTokenVar('manager_id');
        $tag = sprintf(config('cache.category'),$t_id);
        $result =  $this->getCache($tag);
        if ($result != null){
            return $result;
        }
        $result = CategoryModel::getAllCategory($t_id);
        if ($result->isEmpty()){
            throw new CategoryException();
        }
        //加入缓存
        $this->saveToCache($tag,json_encode($result),3600*48);
        return $result;
    }

    /**
     * 更具用户获取分类
     * @return false|\PDOStatement|string|\think\Collection
     */
    public function getCategoryByUser(){
        $wu_id = Token::getCurrentUid();
        $user = WorkUser::getUserByWuID($wu_id);
        $t_id = $user->t_id;
        $result = CategoryModel::getAllCategory($t_id);
        if ($result->isEmpty()){
            $data['code'] = 2002;
            $data['content'] = '';
        }else{
            $data['code'] = 200;
            $data['content'] = $result;
        }
        return json($data);
    }

    /**
     * 根据管理员id获取商品分类
     * @return false|\PDOStatement|string|\think\Collection
     * @throws CategoryException
     */
    public function getCategoryByManager(){
        $manager_id = Token::getCurrentUid();
        $result = CategoryModel::getAllCategory($manager_id);
//        if ($result->isEmpty()){
//            throw new CategoryException();
//        }
        return $result;
    }

    /**
     * 获取分类
     * @param $id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws CategoryException
     */
    public function  getCategory($id){
        (new IDMustBePositiveInt())->goCheck();
        $result = CategoryModel::getCategory($id);
        if (empty($result)){
            throw new CategoryException();
        }
        return $result;
    }


    /**
     * 创建分类
     * @return \think\response\Json
     * @throws CategoryException
     */
    public function createCategory(){
        $validate = new CategoryParameter();
        $dataArray = $validate->getDataByRule(input('post.'));
        $manager_id = Token::getCurrentUid();
        $result = CategoryModel::createCategory($dataArray,$manager_id);
        if (empty($result)){
            throw new CategoryException([
                'code'=>400,
                'msg'=>'添加分类失败',
                'err_code'=>50001
            ]);
        }
        $tag = sprintf(config('cache.category'),$manager_id);
        $this->removeCache($tag);
        $data['code'] = 201;
        $data['content'] = $result;
        $data['error_code'] = 0;
        return json($data);
    }
    /**
     * 更新分类
     * @return \think\response\Json
     * @throws CategoryException
     */
    public function updateCategory(){
        $validate = new CategoryUpdateParameter();
        $dataArray = $validate->getDataByRule(input('post.'));
        $manager_id = Token::getCurrentUid();
        $result = CategoryModel::updateCategory($dataArray,$manager_id);
        if (empty($result)){
            throw new CategoryException([
                'code'=>400,
                'msg'=>'更新分类失败',
                'err_code'=>50001
            ]);
        }
        $tag = sprintf(config('cache.category'),$manager_id);
        $this->removeCache($tag);
        return json(new SuccessMessage());
    }
    /**
     * 删除分类
     * @param $id
     * @return string
     * @throws CategoryException
     * @throws ProductException
     */
    public function deleteCategory($id){
        (new IDMustBePositiveInt())->goCheck();
        $manager_id = Token::getCurrentUid();
        $goods = ProductModel::getProductAllInCategory($id,$manager_id,$page=1,$count=10);
        if (!$goods->isEmpty()){
            throw new ProductException([
                'code'=>400,
                'msg'=>'该分类下，已有商品。该分类不能删除',
                'err_code'=>50002
            ]);
        }
        $result = CategoryModel::deleteCategory($id);
        if ($result){
            $tag = sprintf(config('cache.category'),$manager_id);
            $this->removeCache($tag);
            return json(new SuccessMessage());
        }else{
            throw new CategoryException();
        }
    }
    /**
     * 获取分类的规格信息
     * @return false|\PDOStatement|string|\think\Collection
     * @throws CategoryException
     */
    public function getProperty(){
        $manager_id = Token::getCurrentUid();
        $service = new Property();
        $result =  $service->getProperty($manager_id);
        if ($result->isEmpty()){
            throw new CategoryException();
        }
        return $result;
    }
    /**
     * 获取某个分类下的规格信息
     * @param $c_id
     * @return false|\PDOStatement|string|\think\Collection
     * @throws CategoryException
     */
    public function getPropertyByCategory($id){
        (new IDMustBePositiveInt())->goCheck();
        $service = new Property();
        $result = $service->getPropertyByCategory($id);
//        if ($result->isEmpty()){
//            throw new CategoryException();
//        }
        return $result;
    }
}